<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%String path = request.getContextPath();%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<%--<%@ taglib uri="/WEB-INF/tld/ui.tld" prefix="ui" %>--%>
<%@ taglib uri="/WEB-INF/tld/fmt.tld" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>资管结清明细</title>
    <jsp:include page="../../import.jsp" flush="true"/>
</head>
<body class="iframeBody">
<div class="Wrapper">
    <div id="pageInTab" class="pageInTab">
        <form id="settleDataForm">
            <input type="hidden" id="paySchId" name="paySchId" value="${pay.id}"/>
            <div class="fieldset1 tabel_col clearFix">
                <div class="fieldBox col_50">
                    <div class="label">项目类型</div>
                    <div class="field">
                        <span>${prj.prjTypCdNm}</span>
                    </div>
                </div>
                <div class="fieldBox col_50">
                    <div class="label">承租人</div>
                    <div class="field">
                        <span>${prj.cstNm }</span>
                    </div>
                </div>
                <div class="fieldBox col_50">
                    <div class="label">结清方式</div>
                    <div class="field">
                        <span id="settleWay" name="settleWay">${settleTypNm}</span>
                    </div>
                </div>
                <div class="fieldBox col_50">
                    <div class="label">开始期次</div>
                    <div class="field">
                        <c:if test="${pay.startLsPd!=0}">
                            <span>${pay.startLsPd}</span>
                        </c:if>
                        <c:if test="${pay.startLsPd==0}">
                            到期
                        </c:if>
                    </div>
                </div>
                <div class="fieldBox col_50">
                    <div class="label">融资租赁合同号</div>
                    <div class="field">
                        <span>${prj.lsCntNo}</span>
                    </div>
                </div>
                <div class="fieldBox col_50">
                    <div class="label">保险保证金(元)</div>
                    <div class="field">
                        <span>
                            <fmt:formatNumber value="${pay.insDep/100}" pattern="#,##0.00#"/>
                        </span>
                    </div>
                </div>
                <div class="fieldBox col_50">
                    <div class="label">资方支付表号</div>
                    <div class="field">
                        <span>${pay.paySchNo}</span>
                    </div>
                </div>
                <div class="fieldBox col_50">
                    <div class="label">客户保证金(元)</div>
                    <div class="field">
                        <span>
                            <fmt:formatNumber value="${pay.detAmt/100}" pattern="#,##0.00#"/>
                        </span>
                    </div>
                </div>
                <div class="fieldBox col_100">
                    <input type="hidden" id="ourPaySchListSize" name="ourPaySchListSize" value="${fn:length(pay.ourPaySchList)}"/>
                    <div class="label">我司支付表号</div>
                    <div class="field">
                        <c:forEach items="${pay.ourPaySchList }" var="ourCompanyPaySch">
                            <input type="hidden" name="ourPaySchId" value="${ourCompanyPaySch.id }" />
                            <a href="javascript:detailBtn('${ourCompanyPaySch.id }')" class="link">
                                <span>${ourCompanyPaySch.paySchNo }</span><br/>
                            </a>
                        </c:forEach>
                    </div>
                </div>

                <%--只在资金部维护结清金额、财务核算结清款、财务确认到账节点展示--%>
                <c:if test="${taskDefKey == 'FLOW_0000_065_001_003' || taskDefKey == 'FLOW_0000_065_001_004' || taskDefKey == 'FLOW_0000_065_001_007'}">
                    <div class="fieldBox col_100">
                        <div class="label" role="ligertip">结清对客IRR</div>
                        <div class="field">
		                <span>
                            <c:if test="${empty pay.cstStlIrr}"></c:if>
                            <c:if test="${not empty pay.cstStlIrr}">
                                <fmt:formatNumber type="percent" value="${pay.cstStlIrr}" maxIntegerDigits="2" minFractionDigits="2"/>
                            </c:if>
		                </span>
                        </div>
                    </div>
                </c:if>

                <div class="fieldBox col_100">
                    <div class="label">最终应还金额公式</div>
                    <div class="field">
                        <font color="red">剩余未还本金 + 剩余未还利息 + 尾款 + 其他费用 + 保险违约金金额 + 未核销借款金额 - 剩余客户保证金 - 保险保证金</font>
                    </div>
                </div>
                <div class="fieldBox col_100">
                    <div class="label">最终应还金额(元)</div>
                    <div class="field">
                        <span>
                            <fmt:formatNumber value="${pay.finalPayAmt/100}" pattern="#,##0.00#"/>
                        </span>
                    </div>
                </div>
                <div class="fieldBox col_50">
                    <div class="label">我司与资方结清款(元)</div>
                    <div class="field">
                        <span id="stlAmtOther_span">
                            ${pay.stlAmtOther==null?'':pay.stlAmtOther/100}
                        </span>
                    </div>
                </div>

                <div class="caption">
                    <span class="title">我司与资方结清信息</span>
                </div>
                <div class="fieldBox col_100">
                    <div class="sqPanel">
                        <div id="ligergrid_zf" class="sq-grid"></div>
                    </div>
                </div>

                <div class="caption">
                    <span class="title">已付款项明细信息</span>
                </div>
                <div class="fieldBox col_100">
                    <div class="sqPanel">
                        <div id="ligergrid_fee" class="sq-grid"></div>
                    </div>
                </div>
                <div class="fieldBox col_100">
                    <div class="sqPanel">
                        <div>
                            <div id="ligergrid_payAmt" class="sq-grid sq-grid-noTitle"></div>
                        </div>
                    </div>
                </div>
                <div class="fieldBox col_100">
                    <div class="label">来款合计</div>
                    <div class="field">
                        <span>
                            <c:if test="${pay.totalActPrinAmt+pay.totalActIntAmt==0}">0</c:if>
                            <c:if test="${pay.totalActPrinAmt+pay.totalActIntAmt!=0}">
                                <fmt:formatNumber value="${(pay.totalActPrinAmt+pay.totalActIntAmt)/100}" pattern="#,##0.00#"/>
                            </c:if>
                        </span>
                    </div>
                </div>
                <div class="caption">
                    <span class="title">应还项目信息</span>
                </div>
                <div class="fieldBox col_100">
                    <div class="sqPanel">
                        <div>
                            <div id="ligergrid_shouldPay" class="sq-grid sq-grid-noTitle"></div>
                        </div>
                    </div>
                </div>

                <%-- 结清费用项操作页面 --%>
                <jsp:include page="../../settlement/modifySettleFeeCommon.jsp"/>

                <div class="caption">
                    <span class="title">核算金额校验</span>
                </div>
                <div class="fieldBox col_100">
                    <div class="sqPanel">
                        <div>
                            <div id="ligergrid_checkAmt" class="sq-grid sq-grid-noTitle"></div>
                        </div>
                    </div>
                </div>

                <%--提前结清时显示--%>
                <div class="fieldBox col_100" id="preSettlePayListDiv" style="display: none">
                    <div class="sqPanel">
                        <div id="feePayGrid">
                            <div id="ligergrid_calculate" class="sq-grid"></div>
                        </div>
                    </div>
                </div>
            </div>

            <%--附件--%>
            <jsp:include page="../../settlement/settleFile.jsp" flush="true">
                <jsp:param name="pkId" value="${pay.id}"/>
                <jsp:param name="filePath" value="prjprdpayschm"/>
                <jsp:param name="optAuth" value="${fileAuth}"/>
            </jsp:include>

            <%-- 银行账户维护--%>
            <jsp:include page="settleBankAdd.jsp">
                <jsp:param name="paySchId" value="${pay.id}"/>
                <jsp:param name="bankAct" value="${bankAct}"/>
                <jsp:param name="currentNodeId" value="${taskDefKey}"/>
                <jsp:param name="cstId" value="${pay.cstId}"/>
                <jsp:param name="bizFlag" value="${pay.bizFlag}"/>
            </jsp:include>

            <div class="btnsBox" style="text-align:center">
                <span id="startSettleFlow" class="sq-button sq-button-round operation">${settleTypNm}</span>
                <%--财务核算结清款，保存按钮--%>
                <span id="saveSettleFeeBtn" class="sq-button sq-button-round operation" onclick="saveSettleData()"><i class="sqBtnIco_10"></i>保存</span>
            </div>
        </form>
        <%--财务确认到账节点、分解租金异常节点，资金操作iframe--%>
        <c:if test="${taskDefKey=='FLOW_0000_065_001_007' || taskDefKey=='FLOW_0000_065_001_021' }">
            <iframe frameborder="0" name="" id="" style="width: 100%;" src="<%=path%>/project/financialInst/toAddCapFundPage.do?dataId=${pay.id}&prjId=${prj.id}"></iframe>
        </c:if>
    </div>
</div>
<%-- dialog --%>
<div id="modifyStlAmtOther_Html" style="display:none">
    <form id="modifyStlAmtOthForm">
        <input type="text" style="display: none" id="scheduleId" name="scheduleId" value=""/>
        <input type="text" style="display: none" id="scheduleCd" name="scheduleCd" value=""/>
        <div class="fieldset1 tabel_col clearFix">
            <div class="fieldBox col_100_auto">
                <div class="label">我司与资方结清款</div>
                <div class="field">
                    <input name="rentAmt" id="rentAmt" type="text" class="ui-textbox" value="" onchange="Num(this)" validate="{required:true,number:true}">
                    <span class="requiredSymbol">*</span>
                </div>
            </div>
            <div class="fieldBox col_100_auto">
                <div class="label">我司与资方结清本金</div>
                <div class="field">
                    <input name="principalAmt" id="principalAmt" type="text" class="ui-textbox" value="" onchange="Num(this)" validate="{required:true,number:true}">
                    <span class="requiredSymbol">*</span>
                </div>
            </div>
            <div class="fieldBox col_100_auto">
                <div class="label">我司与资方结清利息</div>
                <div class="field">
                    <input name="interestAmt" id="interestAmt" type="text" class="ui-textbox" value="" onchange="Num(this)" validate="{required:true,number:true}">
                    <span class="requiredSymbol">*</span>
                </div>
            </div>
        </div>
        <div class="btnsBox" style="text-align: center">
            <span class="sq-button sq-button-hasicon" onclick="saveThirdStlInfo()"><i class="sqBtnIco_10"></i>保存</span>
        </div>
    </form>
</div>

<script type="text/javascript">
    var basePath = '<%=path%>';
    var settleTyp = '${settleTyp}';
    var bizFlag = '${pay.bizFlag}';
    var flow = '${flow}';
    var pInstId = '${pInstId}';
    var readOnlyFlag = true;
    var taskDefKey = '${taskDefKey}';
    var calculateGrid, zfScheduleGrid;
    var paySchId = $("#paySchId").val();
    var prjId = '${prj.id}';
    // 页面控制
    $(function () {
        // 默认只读
        $(".operation").hide();
        // 提前结清显示
        if (settleTyp == CommonConstant.SETTLE_TYPE_2) {
            //$("#defaultFeeDiv").show();
            $("#preSettlePayListDiv").show();
            //initDefFeeSettGrid();
            initCalculatePage();
        }
        // 发起结清
        if (taskDefKey == 'FLOW_0000_065_001') {
            $("#fileDetail").show();
            $("#startSettleFlow").show();
        }
        // 财务核算结清款
        if (taskDefKey == 'FLOW_0000_065_001_004') {
            readOnlyFlag = false;
            $("#addBtn").show();
            $("#delBtn").show();
            $("#saveSettleFeeBtn").show();
        }
    });
    $(function () {
        initPaidFeeGrid();
        initPaidRentGrid();
        initShouldPayGrid();
        initCheckAmtGrid();

        if (flow == CommonConstant.C_YN_Y_1) {
            initZFScheduleGrid();
        }

        // 结清按钮点击事件
        $("#startSettleFlow").click(function (event) {
            $.ligerDialog.confirm("确定要发起${settleTypNm}吗？", function (flag) {
                if (flag == false) return;
                var ourPaySchNum = $("#ourPaySchListSize").val();
                var isAllStl = "1";// 0-单台结清，1-全部结清
                if (ourPaySchNum > 1) {
                    $.ligerDialog.confirm('<font color="red" style="font-weight:bold;">当前资管项目下有多台设备，请您确定是否全部结清？</font>', function (yes) {
                        if (yes) {
                            isAllStl = "1";
                        } else {
                            isAllStl = "0";
                        }
                        callSettleFlow(isAllStl);
                    });
                } else {
                    callSettleFlow(isAllStl);
                }
            });
        });
    });

    // 请求发起结清流程
    function callSettleFlow(isAllStl) {
        var data = {};
        data["payPd"] = '${pay.startLsPd}';
        data["isAllStl"] = isAllStl;

        if (settleTyp == CommonConstant.SETTLE_TYPE_2) {
            data["settFlag"] = "pre";
            data["discountAmt"] = '${pay.discountAmt / 100}';
            requestSettle(data, "/project/prjprdpayschm/applyPreSett.do", function (msg) {
                // 关闭当前tab页面
                Remove_navTab();
                // 回调
                var callback = frameElement.W2W.callback;
                callback();
            });
        } else if (settleTyp == CommonConstant.SETTLE_TYPE_1) {
            requestSettle(data, "/project/prjprdpayschm/applyNormalSett.do", function (msg) {
                // 关闭当前tab页面
                Remove_navTab();
                var callback = frameElement.W2W.callback;
                callback();
            });
        } else {
            UIUtils.alertErrorHold1("结清类型参数错误！");
        }
    }

    function requestSettle(data, url, callback) {
        data["totalSettAmt"] = $("#totalSettAmt").text().trim();
        data["paySchId"] = paySchId;
        var wait_dialog;
        $.ajax({
            type: 'post',
            dataType: 'json',
            data: data,
            url: basePath + url,
            beforeSend: function () {
                wait_dialog = $.ligerDialog.SQalert({
                    content: LogUtils.LOG_CMM_DATA_LOADING,
                    SQ_type: "waitting"
                });
            },
            success: function (msg) {
                wait_dialog.close();
                if (msg.success == 1) {
                    $.ligerDialog.SQalert({
                        content: msg.info,
                        SQ_type: "success",
                        SQ_showButtons: true,
                        SQ_onBtnclick: callback(msg)
                    });
                } else {
                    UIUtils.alertErrorHold1(msg.info);
                }
            }
        });
    }

    function initZFScheduleGrid() {
        var isHaveInterface = '${isHaveInterface}';
        zfScheduleGrid = $("#ligergrid_zf").ligerGrid({
            method: 'get',
            parms: {paySchId: paySchId, flow: flow, pInstId: pInstId},
            url: basePath + '/project/financialInst/zfScheduleList.do',
            columns: [
                {display: '', name: 'scheduleNm', minWidth: 140},
                {display: '发生时间', name: 'completeTimeNm', minWidth: 140},
                {display: '我司与资方结清款', name: 'rentAmt', minWidth: 60, render: renderAmt, type: 'currency'},
                {display: '我司与资方结清本金', name: 'principalAmt', minWidth: 60, render: renderAmt, type: 'currency'},
                {display: '我司与资方结清利息', name: 'interestAmt', minWidth: 60, render: renderAmt, type: 'currency'},
                {display: '操作人', name: 'modifyUser', minWidth: 60},
                {display: '创建时间', name: 'crtTm', minWidth: 60, render: function (rowdata, rowindex, value) {
                        if (value != null) {
                            var date = new Date(value);
                            return DateUtils.formatDate(date, DateUtils.YYYY_MM_DDHHMMSS);
                        }
                        return value;
                    }
                },
                {
                    display: '', name: 'opt', minWidth: 60, render: function (rowdata, rowindex, value) {
                        var other = "";
                        if (rowdata.scheduleCd == '15'
                            && (taskDefKey == 'FLOW_0000_065_001_003'
                                || taskDefKey == 'FLOW_0000_065_001_007'
                                || taskDefKey == 'FLOW_0000_065_001_021')) {
                            // 资金部维护结清金额 || 财务确认到账 || 分解租金异常
                            if (isHaveInterface == '1') {
                                other += '<a class="sq-button-hasicon" href="javascript:void(0);" onclick="reacquireFromThird('+rowindex+','+rowdata.scheduleCd+');"><i class="sqBtnIco_48"></i>重新获取</a>';
                            } else {
                                other += '<a class="sq-button-hasicon" href="javascript:void(0);" onclick="openDialogOfModifyStlAmt('+rowindex+','+rowdata.scheduleCd+')"><i class="sqBtnIco_4"></i>修改</a>';
                            }
                        }
                        if (rowdata.scheduleCd == '53' && (taskDefKey == 'FLOW_0000_065_001_022' || taskDefKey == 'FLOW_0000_065_001_029')) {
                            // 资金部确认 or 三方结清失败异常
                            if (isHaveInterface == '1') {
                                other += '<a class="sq-button-hasicon" href="javascript:void(0);" onclick="reacquireFromThird('+rowindex+','+rowdata.scheduleCd+');"><i class="sqBtnIco_48"></i>重新获取</a>';
                            } else {
                                other += '<a class="sq-button-hasicon" href="javascript:void(0);" onclick="openDialogOfModifyStlAmt('+rowindex+','+rowdata.scheduleCd+')"><i class="sqBtnIco_4"></i>修改</a>';
                            }
                        }
                        return other;
                    }
                }
            ],
            usePager: false,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            height: 300,
            heightDiff: -2,
            enabledEdit: false,
            isScroll: false,
            checkbox: false,
            rownumbers: true,
            allowUnSelectRow: false,
            alternatingRow: false,
            onBeforeShowData: function(currentData){
                // 防止在(资金部维护结清金额 || 财务确认到账 || 分解租金异常)节点时，没有生成数据，造成无法在页面点击"重新获取"的问题
                // 解决：push一条空行数据，让"重新获取"按钮展示出来
                if (currentData.total == 0 && (taskDefKey == 'FLOW_0000_065_001_003'
                    || taskDefKey == 'FLOW_0000_065_001_007'
                    || taskDefKey == 'FLOW_0000_065_001_021')) {
                    // 资金部维护结清金额 || 财务确认到账 || 分解租金异常
                    currentData.rows.push({"scheduleCd": "15"});
                }
            }
        });
    }

    var errorCnt = 0, errorMax = 3;
    function reacquireFromThird(rowindex, scheduleCd) {
        top.$.ligerDialog.confirm('<font color=\"red\" style=\"font-weight:bold;font-size:14px;\">确定要调用资方接口重新获取吗？</font>', function (flag) {
            if (flag == false) return;
            var wait_dialog;
            $.ajax({
                type: 'post',
                dataType: 'json',
                data: {prjId: prjId, paySchId: paySchId, scheduleCd: scheduleCd},
                url: basePath + '/project/financialInst/reacquire.do',
                beforeSend: function () {
                    wait_dialog = $.ligerDialog.SQalert({
                        content: LogUtils.LOG_CMM_DATA_LOADING,
                        SQ_type: "waitting"
                    });
                },
                success: function (msg) {
                    wait_dialog.close();
                    if (msg.success == 1) {
                        UIUtils.alertSuccessHold1(msg.info);
                        zfScheduleGrid.reload();
                    } else if (msg.success == 2) {
                        errorCnt++;
                        $.ligerDialog.SQalert({content: msg.info, SQ_showButtons: true, SQ_type: "warning", onClose: function () {
                            if (rowindex == null || errorCnt < errorMax) {
                                zfScheduleGrid.reload();
                            } else if(errorCnt >= errorMax) {
                                $.ligerDialog.SQconfirm("第三方接口出现异常，是否要手动维护？", function (yes) {
                                    if (yes) {
                                        openDialogOfModifyStlAmt(rowindex, scheduleCd);
                                    }
                                });
                            }
                        }});
                    } else {
                        UIUtils.alertErrorHold1(msg.info);
                    }
                }
            });
        });
    }

    // 初始化已付费用数据
    function initPaidFeeGrid() {
        var feeListPage = '${feeListPage}';
        try {
            feeListPage = JsonUtils.parse(feeListPage);
        } catch (error) {
            UIUtils.alertErrorHold1("初始化已付费用数据错误！");
            return;
        }
        $("#ligergrid_fee").ligerGrid({
            data: feeListPage,
            columns: [
                {display: '项目', name: 'feeTypCdNm', minWidth: 140},
                {display: '应收金额(元)', name: 'feeAmt', minWidth: 140, render: renderAmt, type: 'currency'},
                {display: '已收金额(元)', name: 'paidUpAmt', minWidth: 60, render: renderAmt, type: 'currency'}
            ],
            usePager: false,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            height: 300,
            heightDiff: -2,
            enabledEdit: false,
            isScroll: false,
            checkbox: false,
            rownumbers: true,
            allowUnSelectRow: false,
            alternatingRow: false
        });
    }
    // 初始化已付本金、利息、罚息数据
    function initPaidRentGrid() {
        $("#ligergrid_payAmt").ligerGrid({
            data: {
                "rows": [
                    {
                        "feeTypCdNm": "本金",
                        "feeAmt": '${pay.totalPrinAmt}',
                        "paidUpAmt": "${pay.totalActPrinAmt}"
                    },
                    {
                        "feeTypCdNm": "利息",
                        "feeAmt": '${pay.totalIntAmt}',
                        "paidUpAmt": "${pay.totalActIntAmt}"
                    },
                    {
                        "feeTypCdNm": "已交罚息合计",
                        "feeAmt": '${pay.penaltyAmt}',
                        "paidUpAmt": "${pay.payAmount}"
                    }
                ],
                "total": 3
            },
            columns: [
                {display: '项目', name: 'feeTypCdNm', minWidth: 140},
                {display: '应收金额(元)', name: 'feeAmt', minWidth: 140, render: renderAmt, type: 'currency'},
                {display: '已收金额(元)', name: 'paidUpAmt', render: renderAmt, minWidth: 60, type: 'currency'}
            ],
            usePager: false,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            heightDiff: -2,
            enabledEdit: false,
            isScroll: false,
            checkbox: false,
            frozen: false,
            rownumbers: true,
            allowUnSelectRow: false,
            alternatingRow: false
        });
    }
    // 初始化应还列表数据
    function initShouldPayGrid() {
        $("#ligergrid_shouldPay").ligerGrid({
            data: getShouldPayData(),
            columns: [
                {display: '项目', name: 'feeTypCdNm', minWidth: 140},
                {
                    display: '应收金额(元)', name: 'feeAmt', minWidth: 140, type: 'currency',
                    render: function (item) {
                        var feeAmt = item.feeAmt/100;
                        var ret = "";
                        if (item.capFlow == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT) {
                            ret = "<span style='color:red'>-" +
                                "￥" + FormatMoney((parseFloat(feeAmt)).toFixed(2))
                                + "</span>";
                        } else {
                            ret = "￥" + FormatMoney((parseFloat(feeAmt)).toFixed(2));
                        }
                        return ret;
                    }
                },
                {display: '已收金额(元)', name: 'paidUpAmt', minWidth: 60, type: 'currency'}
            ],
            usePager: false,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            heightDiff: -2,
            enabledEdit: false,
            isScroll: false,
            checkbox: false,
            rownumbers: true,
            frozen: false,
            allowUnSelectRow: false,
            alternatingRow: false
        });
    }
    function getShouldPayData() {
        var subFeeAmt = '${subFeeAmtTotalList}';
        subFeeAmt = JsonUtils.parse(subFeeAmt);
        var shouldPayData = {
            "rows": [
                {
                    "feeTypCdNm": "风险保证金",
                    "feeAmt": '${pay.rickDep}',
                    "paidUpAmt": ""
                },
                {
                    "feeTypCdNm": "截止发起日应交逾期租金",
                    "feeAmt": '${pay.overdueAmt}',
                    "paidUpAmt": ""
                },
                {
                    "feeTypCdNm": "截止发起日应交逾期罚息",
                    "feeAmt": '${pay.penaltyAmt}',
                    "paidUpAmt": ""
                },
                {
                    "feeTypCdNm": "自结清期剩余本金",
                    "feeAmt": '${pay.lastPrintAmt}',
                    "paidUpAmt": ""
                },
                {
                    "feeTypCdNm": "自结清期剩余利息",
                    "feeAmt": '${pay.lastIntAmt}',
                    "paidUpAmt": ""
                },
                {
                    "feeTypCdNm": "尾款",
                    "feeAmt": '${pay.lastPayAmt}',
                    "paidUpAmt": ""
                }
            ],
            "total": 0
        }
        for (var i = 0; i < subFeeAmt.length; i++) {
            var obj = subFeeAmt[i];
            var json = {};
            json.feeTypCdNm = obj.feeTypCdNm;
            json.feeAmt = obj.feeAmt;
            json.paidUpAmt = obj.paidUpAmt;
            json.capFlow = obj.capFlow;
            shouldPayData.rows.push(json);
        }
        return shouldPayData;
    }

    function initCheckAmtGrid() {
        $("#ligergrid_checkAmt").ligerGrid({
            data: {
                "rows": [
                    {
                        "feeTypCdNm": "支付表本金合计",
                        "feeAmt": '${pay.totalPrinAmt}',
                        "paidUpAmt": ""
                    },
                    {
                        "feeTypCdNm": "支付表利息合计",
                        "feeAmt": '${pay.totalIntAmt}',
                        "paidUpAmt": ""
                    },
                    {
                        "feeTypCdNm": "核算金额校验",
                        "feeAmt": '${pay.checkPayAmt}',
                        "paidUpAmt": ""
                    }

                ],
                "total": 3
            },
            columns: [
                {display: '项目', name: 'feeTypCdNm', minWidth: 140},
                {display: '应收金额(元)', name: 'feeAmt', minWidth: 140, type: 'currency', render: renderAmt},
                {display: '已收金额(元)', name: 'paidUpAmt', minWidth: 60, type: 'currency'}
            ],
            usePager: false,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            heightDiff: -2,
            enabledEdit: false,
            isScroll: false,
            checkbox: false,
            rownumbers: true,
            frozen: false,
            allowUnSelectRow: false,
            alternatingRow: false
        });
    }
    // 初始化提前结清合并期次后的支付表列表
    function initCalculatePage() {
        var listPage = '${listPage}';
        try {
            listPage = JsonUtils.parse(listPage);
        } catch (error) {
            UIUtils.alertErrorHold1("初始化提前结清合并期次后的支付表错误！");
            return;
        }
        calculateGrid = $("#ligergrid_calculate").ligerGrid({
            data: listPage,
            columns: [
                {display: '支付时间', name: 'payDt', width: 120, render: renderDate},
                {display: '期次', name: 'payPd', width: 80},
                {display: '租金', name: 'rntAmt', minWidth: 140, render: renderAmt, type: 'currency', enabledSort: true,
                    totalSummary:
                        {
                            render: function (rowdata, column, cell) {
                                var sum = renderAmt(null, null, rowdata.sum);
                                return '<div style="color:red">合计租金：' + sum + '</div>';
                            },
                            align: 'left'
                        }
                },
                {display: '本金', name: 'prinAmt', minWidth: 60, render: renderAmt, type: 'currency',
                    totalSummary:
                        {
                            render: function (rowdata, column, cell) {
                                var sum = renderAmt(null, null, rowdata.sum);
                                return '<div style="color:red">合计本金：' + sum + '</div>';
                            },
                            align: 'left'
                        }
                },
                {display: '利息', name: 'intAmt', minWidth: 140, render: renderAmt, type: 'currency',
                    totalSummary:
                        {
                            render: function (rowdata, column, cell) {
                                var sum = renderAmt(null, null, rowdata.sum);
                                return '<div style="color:red">合计利息：' + sum + '</div>';
                            },
                            align: 'left'
                        }
                },
                {display: '剩余本金', name: 'remPrinAmt', minWidth: 140, render: renderAmt, type: 'currency'},
            ],
            usePager: false,
            pageSize: 10,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            height: 300,
            heightDiff: -2,
            //isScroll: false,
            checkbox: false,
            enabledEdit: false,
            rownumbers: true
        });
    }
    // 查看支付表详情
    function detailBtn(pSchId) {
        Add_navTab('tab_prj_quat_prps' + pSchId, '查看支付表', basePath+'/project/financialInst/enterPaySchDetailPage.do?prjId=' + prjId + '&paySchId=' + pSchId);
    }

    // open modify stlAmtOther dialog
    var stlAmtOther_dialog;
    function openDialogOfModifyStlAmt(rowindex, scheduleCd) {
        var rowdata = zfScheduleGrid.getRow(rowindex);
        $("#scheduleId").val(rowdata.id);
        $("#scheduleCd").val(scheduleCd);
        $("#rentAmt").val(rowdata.rentAmt == null ? '' : rowdata.rentAmt / 100);
        $("#principalAmt").val(rowdata.principalAmt == null ? '' : rowdata.principalAmt / 100);
        $("#interestAmt").val(rowdata.interestAmt == null ? '' : rowdata.interestAmt / 100);
        stlAmtOther_dialog = $.ligerDialog.SQopen({
            width: 400,
            height: 260,
            title : '修改我司与资方结清金额信息',
            target : $('#modifyStlAmtOther_Html'),
            onHideDialog: function () {
                //clearLigerForm("modifyStlAmtOthForm");
            }
        });
    }

    // 保存我司与资方结清款
    function saveThirdStlInfo(){
        $("#modifyStlAmtOthForm").ligerForm({
            validate: true
        });
        var form = liger.get("modifyStlAmtOthForm");
        if (!form.valid()) {
            top.$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_MUST_FIX_ITEM_INFO, SQ_type: "warning"});
            return false; //验证不通过，不执行以下代码
        }
        var data = form.getData();
        data["paySchId"] = paySchId;
        data["pInstId"] = pInstId;
        top.$.ligerDialog.confirm("确定要修改吗？", function (flag) {
            if (flag == false) return;
            var wait_dialog;
            $.ajax({
                type: 'post',
                dataType: 'json',
                data: data,
                url: basePath + '/project/financialInst/modifyStlAmtOther.do',
                beforeSend: function () {
                    wait_dialog = $.ligerDialog.SQalert({
                        content: LogUtils.LOG_CMM_DATA_LOADING,
                        SQ_type: "waitting"
                    });
                },
                success: function (msg) {
                    wait_dialog.close();
                    if (msg.success == 1) {
                        UIUtils.alertSuccessHold1(msg.info);
                        zfScheduleGrid.reload();
                        $("#stlAmtOther_span").text($("#rentAmt").val());
                    } else {
                        UIUtils.alertErrorHold1(msg.info);
                    }
                    stlAmtOther_dialog.hidden();
                }
            });
        });
    }

    //格式化为人民币格式
    function renderAmt(rowdata, rowindex, value) {
        if (null !== value && value !== 'undefined' && value !== "" && value != undefined) {
            if (typeof Number(value) == 'number') {
                var h = "￥" + FormatMoney((parseFloat(value/100)).toFixed(2));
                return h;
            }
        }
    }
    //格式化时间
    function renderDate(rowdata, index, value){
        var dateStr = "";
        if(null != value){
            var date = new Date(value);
            dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DD);
        }
        return dateStr;
    }
    //允许输入数字和小数点
    function Num(obj){
        obj.value = obj.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
        obj.value = obj.value.replace(/^\./g,""); //验证第一个字符是数字
        obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
        obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
        obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
    }


    // iframe自适应高度
    $(function(){
        var iframes = document.getElementsByTagName('iframe');
        for (var i = 0, j = iframes.length; i < j; ++i) {
            // 放在闭包中，防止iframe触发load事件的时候下标不匹配
            (function (_i) {
                iframes[_i].onload = function () {
                    this.contentWindow.onbeforeunload = function () {
                        iframes[_i].style.visibility = 'hidden';
                        // iframes[_i].style.display = 'none';

                        iframes[_i].setAttribute('height', 'auto');
                    };
                    this.setAttribute('height', this.contentWindow.document.body.scrollHeight);

                    this.style.visibility = 'visible';
                    // this.style.display = 'block';
                };
            })(i);
        }
    });
</script>
</body>
</html>
